﻿/*
   Created 2009 March 13 Randall Maas
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System .Net;
using System .Net . Sockets;
using SKYPE4COMLib;

/// <summary>
/// portion of class to interface a microphone to Skype
/// </summary>
static partial class Microphone
{
   /// <summary>
   /// Our connection to Skype
   /// </summary>
   internal static Skype skype = new Skype();

   const int Protocol = 8;

   const int MicOutPort = 3755;

   /// <summary>
   /// A server socket we use to receive connections to skype
   /// </summary>
   static volatile Socket MicOutServerSocket = new Socket(AddressFamily.InterNetwork
                                                , SocketType.Stream
                                                , ProtocolType.Tcp
                                                );

   static Microphone()
   {
      // Configure the server socket to answer calls
      MicOutServerSocket .Bind(new IPEndPoint(IPAddress.Any, MicOutPort));

      // Configure the maximum number of callers on hold
      MicOutServerSocket.Listen(1);
      // And start answering connection requests
      MicOutServerSocket.BeginAccept(new AsyncCallback(OnMicConnect), null);

      _ISkypeEvents_Event events = (_ISkypeEvents_Event)skype;
      events. AttachmentStatus += OnSkypeAttachmentStatus;            
      skype . CallStatus       += OnSkypeCallStatus;
      skype . Attach(Protocol, false);
   }


   internal static void Stop()
   {
      // Restore skype's auto gain setting
      if (Pre_Set)
        Microphone . skype . Settings . AGC = Pre_SkypeAutoGain ;

      Socket S = MicOutServerSocket ;
      MicOutServerSocket = null;
      S . Close();
      StopMicrophone();
   }

   /// <summary>
   /// Receives notifications about socket connect requests
   /// </summary>
   /// <param name="e"></param>
   static void OnMicConnect(IAsyncResult e)
   {
      // Get the data socket
      if (null == MicOutServerSocket)
        return;
      outStream = MicOutServerSocket.EndAccept(e);
      outStream . NoDelay = true;

      Program . Options . CallStart();

      // Start the microphone
      StartMicrophone(SkypeSidetone . Properties.Settings . Default . SideTone);

      // Listen for more!
      // And start answering connection requests
      MicOutServerSocket.BeginAccept(new AsyncCallback(OnMicConnect), null);
   }

   /// <summary>
   /// Saved value of skype's autogain setting
   /// </summary>
   static bool Pre_SkypeAutoGain;

   internal static bool Pre_Set = false;

   /// <summary>
   /// This is called when Skype attaches to this program
   /// </summary>
   /// <param name="status"></param>
   static void OnSkypeAttachmentStatus(TAttachmentStatus status)
   {
      if (status == TAttachmentStatus.apiAttachAvailable)
        skype . Attach(Protocol, false);
      else if (status == TAttachmentStatus.apiAttachSuccess)
        {
           // Ready to go
           if (!Pre_Set)
             {
                // If skype isn't running yet, this will block
                Pre_Set = true;
                Pre_SkypeAutoGain = Microphone . skype . Settings . AGC;
             }
           Microphone . skype . Settings . AGC = SkypeSidetone . Properties.Settings . Default . SkypeAutoGain;
        }
   }

   /// <summary>
   /// The socket used to send data samples out.  Sounds samples are sent as
   /// PCM 16-bit (little endian) samples at 16000/per second
   /// </summary>
   static Socket outStream;


   /// <summary>
   /// A delegate called when Skype initiates a phone call
   /// </summary>
   /// <param name="call"></param>
   /// <param name="status"></param>
   static void OnSkypeCallStatus(Call call, TCallStatus status)
   {
      if (status == TCallStatus.clsInProgress)
        {
           // Tell skype to use us as the microphone
           call . set_InputDevice(TCallIoDeviceType.callIoDeviceTypeSoundcard, "");
           call . set_InputDevice(TCallIoDeviceType.callIoDeviceTypePort, MicOutPort.ToString());
        }
      else if (status == TCallStatus.clsFinished)
        {
           StopMicrophone();
           if (null != outStream)
             outStream.Close();
           outStream = null;
           Program . Options . CallEnd();
        }
   }

}
